package com.jic.order.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.common.utils.IDUtils;
import com.jic.market.api.rest.CouponRestApi;
import com.jic.market.api.rest.GrouponRestApi;
import com.jic.market.api.rest.SeckillRestApi;
import com.jic.market.request.rest.coupon.UseCouponRequest;
import com.jic.market.request.rest.groupon.LaunchOrJoinGrouponRequest;
import com.jic.market.request.rest.groupon.PostPayGroupInstDetailRequest;
import com.jic.market.request.rest.seckill.CheckSeckillRequest;
import com.jic.market.response.rest.groupon.LaunchOrJoinGrouponResponse;
import com.jic.member.api.rest.MemberGrowthOperationApi;
import com.jic.member.api.rest.MemberInformationApi;
import com.jic.member.api.rest.MememberActionApi;
import com.jic.member.api.rest.MememberApi;
import com.jic.member.request.MeinformationRequest;
import com.jic.member.request.MemberIntegralRestRequest;
import com.jic.member.request.ObtainOrConsumptionGrowthRequest;
import com.jic.member.response.MememberUserResponse;
import com.jic.order.base.BaseService;
import com.jic.order.entity.*;
import com.jic.order.enums.*;
import com.jic.order.exception.OrderException;
import com.jic.order.mapper.*;
import com.jic.order.model.OrderModel;
import com.jic.order.model.ParentOrderModel;
import com.jic.order.model.domain.BuyerModel;
import com.jic.order.model.domain.OperateModel;
import com.jic.order.model.domain.OrderBaleModel;
import com.jic.order.model.domain.OrderBaleModel.OrderBaleDetailModel;
import com.jic.order.model.domain.OrderDeliverModel;
import com.jic.order.model.domain.OrderDeliverModel.OrderDeliverDetailModel;
import com.jic.order.model.domain.OrderGoodsModel;
import com.jic.order.model.domain.SellerModel;
import com.jic.order.request.*;
import com.jic.order.request.SendGoodsRequest.BaleDetailInfo;
import com.jic.order.request.SendGoodsRequest.BaleInfo;
import com.jic.order.rest.response.*;
import com.jic.order.service.OrderBaleDeliveryService;
import com.jic.order.service.OrderOperateService;
import com.jic.order.utils.SerialNoUtil;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import com.jic.product.rest.response.ProductInfoResponse;
import com.jic.product.store.request.MStoreFrozenRequest;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class OrderOperateServiceImpl extends BaseService implements OrderOperateService {

    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Resource
    private SeckillRestApi seckillRestApi;
    @Resource
    private GrouponRestApi grouponRestApi;
    @Resource
    private ProductListApi productListApi;
    @Resource
    private MememberActionApi mememberActionApi;
    @Resource
    private CouponRestApi couponRestApi;
    @Resource
    private MemberGrowthOperationApi memberGrowthOperationApi;
    @Resource
    private MemberInformationApi memberInformationApi;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private OrderParentMapper orderParentMapper;
    @Autowired
    private OrderExamineMapper orderExamineMapper;
    @Autowired
    private OrderBaleDeliveryService orderBaleDeliveryService;
    @Autowired
    private OrderProcessLogMapper orderProcessLogMapper;
    @Autowired
    private GrouponRestApi getGrouponRestApi;
    @Autowired
    private OrderBaleMapper orderBaleMapper;
    @Autowired
    private OrderBaleDeliveryMapper orderBaleDeliveryMapper;
    @Autowired
    private MememberApi mememberApi;

    @Override
    public RestResult<String> createOrder(CreateParentOrderRequest request) {
        log.info("创建订单，request={}", JSON.toJSONString(request));
        OperateModel operate = new OperateModel(OperatorActionEnum.USER_CREATE, request.getSerialNo());
        operate.setOperator(request.getBuyerId());
        operate.setOperatorName(request.getBuyerUsername());
        operate.setOperatorLog("买家创建订单");
        return executeOperate(operate, new TemplateService<String, ParentOrderModel>() {
            @Override
            public ParentOrderModel init() {
                return new ParentOrderModel();
            }

            @Override
            public String process(ParentOrderModel model) {
                model.setParentOrderNo(SerialNoUtil.genParentOrderNo());
                if (null != request.getOrderType() && request.getOrderType() == 1) {
                    model.setOrderStatus(OrderStatusEnum.ALREADY_PAY.getCode());
                } else {
                    model.setOrderStatus(OrderStatusEnum.WAIT_PAY.getCode());
                }

                BeanUtils.copyProperties(request, model);

                List<CreateOrderRequest> orderRequestList = request.getCreateOrderRequestList();
                if (null == orderRequestList || orderRequestList.isEmpty()) {
                    log.error("订单信息为空");
                    throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "订单信息为空");
                }

                List<OrderModel> orderModelList = new ArrayList<>();
                for (CreateOrderRequest orderRequest : orderRequestList) {
                    OrderModel orderModel = new OrderModel();
                    orderModel.setOrderNo(SerialNoUtil.genOrderNo());
                    if (null != request.getOrderType() && request.getOrderType() == 1) {
                        orderModel.setOrderType(request.getOrderType());
                        orderModel.setOrderStatus(OrderStatusEnum.ALREADY_PAY.getCode());
                    } else {
                        orderModel.setOrderStatus(OrderStatusEnum.WAIT_PAY.getCode());
                    }
                    orderModel.setSerialNo(model.getSerialNo());
                    orderModel.setParentOrderNo(model.getParentOrderNo());
                    orderModel.setSaleChannel(model.getSaleChannel());
                    orderModel.setBuyTime(new Date());
                    BeanUtils.copyProperties(orderRequest, orderModel);
                    BuyerModel buyerModel = new BuyerModel();
                    BeanUtils.copyProperties(request, buyerModel);
                    buyerModel.setBuyerRealname(request.getReceiverName());
                    buyerModel.setBuyerUsername(request.getReceiverName());
                    SellerModel sellerModel = new SellerModel();
                    BeanUtils.copyProperties(orderRequest, sellerModel);
                    orderModel.setBuyerModel(buyerModel);
                    orderModel.setSellerModel(sellerModel);
                    orderModel.setProductType(request.getProductType());
                    List<FrontParentOrderGoodsRequest> orderGoodsRequestList = orderRequest.getGoodsList();
                    if (null == orderGoodsRequestList || orderGoodsRequestList.isEmpty()) {
                        log.error("订单商品信息为空");
                        throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "订单商品信息为空");
                    }
                    List<OrderGoodsModel> orderGoodsModelList = new ArrayList<>();
                    for (FrontParentOrderGoodsRequest orderGoodsRequest : orderGoodsRequestList) {
                        OrderGoodsModel orderGoodsModel = new OrderGoodsModel();
                        BeanUtils.copyProperties(orderGoodsRequest, orderGoodsModel);
                        // 充值手机号
                        orderGoodsModel.setVirtualPhone(request.getVirtualPhone());

                        orderGoodsModelList.add(orderGoodsModel);
                        // 查询商品是否组合商品
                        RestResult<ProductAfterInfoByIdResponse> restResult = productListApi.queryProductInfoById(orderGoodsRequest.getGoodsId());
                        ProductAfterInfoByIdResponse productAfterInfoByIdResponse = restResult.getData();
                        if (productAfterInfoByIdResponse != null &&
                                productAfterInfoByIdResponse.getType() != null &&
                                (productAfterInfoByIdResponse.getType() == 3 || productAfterInfoByIdResponse.getType() == 4)) {
                            RestResult<List<ProductAfterInfoByIdResponse>> listRestResult = productListApi.queryProductInfoByParentId(orderGoodsRequest.getGoodsId());
                            if (CollectionUtils.isNotEmpty(listRestResult.getData())) {
                                for (ProductAfterInfoByIdResponse productAfterInfoByIdResponse1 : listRestResult.getData()) {
                                    OrderGoodsModel orderGoodsModel2 = new OrderGoodsModel();
                                    orderGoodsModel2.setGoodsName(productAfterInfoByIdResponse1.getChineseName());
                                    orderGoodsModel2.setGoodsId(productAfterInfoByIdResponse1.getProductId());
                                    orderGoodsModel2.setSaleUnitPrice(productAfterInfoByIdResponse1.getMarketPrice());
                                    orderGoodsModel2.setGoodsNum(1);
                                    orderGoodsModel2.setGoodsType(1);
                                    orderGoodsModel2.setGoodsImgUrl(productAfterInfoByIdResponse1.getPictureUrl());
                                    orderGoodsModelList.add(orderGoodsModel2);
                                }
                            }
                        }

                    }
                    orderModel.setOrderGoodsModelList(orderGoodsModelList);
                    orderModelList.add(orderModel);
                }
                model.setOrderModelList(orderModelList);
                return model.getParentOrderNo();
            }
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<String> createSpikeOrder(CreateSpikeOrderRequest request) {
        log.info("创建秒杀订单，request={}", JSON.toJSONString(request));

        // 获取用户id
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + request.getToken());
        if (StringUtils.isEmpty(userStr)) {
            return RestResult.error("4000", "登录失效");
        }
        Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
        String userId = userMap.get("id").toString();
        String userName = userMap.get("username") == null ? "" : userMap.get("username").toString();

        // 校验秒杀商品
        CheckSeckillRequest checkSeckillRequest = new CheckSeckillRequest();
        checkSeckillRequest.setMpId(request.getMpId());
        checkSeckillRequest.setTimeId(request.getTimeId());
        checkSeckillRequest.setPromotionId(request.getPromotionId());
        RestResult<Boolean> booleanRestResult = seckillRestApi.checkSeckillProduct(checkSeckillRequest);
        if (booleanRestResult.getCode().equals("9999")) {
            return RestResult.error("9999", booleanRestResult.getMsg());
        }

        RestResult<ProductAfterInfoByIdResponse> productInfoById = productListApi.queryProductInfoById(request.getMpId());
        // 创建秒杀订单
        if (null != productInfoById.getData()) {
            Date currentTime = new Date();
            // 1.创建父订单
            OrderParent orderParent = new OrderParent();
            BeanUtils.copyProperties(request, orderParent);
            orderParent.setOrderStatus(OrderStatusEnum.WAIT_PAY.getCode());
            orderParent.setParentOrderNo(SerialNoUtil.genParentOrderNo());
            orderParent.setVersion(1);
            orderParent.setCreator(Long.parseLong(userId));
            orderParent.setCreateName(userName);
            orderParent.setCreateTime(currentTime);
            orderParent.setDeleteFlag(0);
            long orderParentFlag = orderParentMapper.insert(orderParent);
            if (orderParentFlag == 0) {
                return RestResult.error("9999", "创建订单失败!");
            }

            // 使用优惠券
            if (request.getPromotionType() == 11) {
                UseCouponRequest useCouponRequest = new UseCouponRequest();
                useCouponRequest.setUserId(userId);
                useCouponRequest.setCouponCode(request.getPromotionId());
                useCouponRequest.setOrderCode(orderParent.getParentOrderNo());
                RestResult<Boolean> booleanRestResult1 = couponRestApi.useCoupons(useCouponRequest);
                if ("9999".equals(booleanRestResult.getCode())) {
                    return RestResult.error("9999", booleanRestResult1.getMsg());
                }
            }

            // 2.创建子订单
            Order order = new Order();
            BeanUtils.copyProperties(request, order);
            order.setParentOrderNo(orderParent.getParentOrderNo());
            order.setOrderNo(SerialNoUtil.genOrderNo());
            order.setOrderStatus(OrderStatusEnum.WAIT_PAY.getCode());
            order.setMark(request.getMark());
            order.setVersion(1);
            order.setCreator(Long.parseLong(userId));
            order.setCreatorName(userName);
            order.setCreateTime(currentTime);
            order.setOrderType(0);
            order.setDeleteFlag(true);
            order.setDeptId(productInfoById.getData().getDeptId());
            long orderFlag = orderMapper.insert(order);
            if (orderFlag == 0) {
                return RestResult.error("9999", "创建订单失败!");
            }

            // 3.创建订单商品明细
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderNo(order.getOrderNo());
            orderGoods.setGoodsId(request.getMpId());
            orderGoods.setGoodsName(productInfoById.getData().getChineseName());
            orderGoods.setGoodsImgUrl(productInfoById.getData().getPictureUrl());
            orderGoods.setGoodsType(productInfoById.getData().getType());
            orderGoods.setGoodsNum(1);
            orderGoods.setWaitTransferDeliverNum(1);
            orderGoods.setSaleUnitPrice(productInfoById.getData().getMarketPrice());
            orderGoods.setDiscountUnitPrice(request.getDiscountTotalAmount());
            orderGoods.setBuyUnitPrice(request.getBuyTotalAmount());
            orderGoods.setExpressUnitFee(request.getExpressTotalFee());
            orderGoods.setActualPayTotalAmount(request.getActualPayTotalAmount());
            orderGoods.setMark(request.getMark());
            orderGoods.setVersion(1);
            orderGoods.setCreator(Long.parseLong(userId));
            orderGoods.setCreateName(userName);
            orderGoods.setCreateTime(currentTime);
            orderGoods.setDeleteFlag(0);
            orderGoods.setDeptId(productInfoById.getData().getDeptId());
            orderGoods.setUnitName(productInfoById.getData().getUnitName());
            orderGoods.setPropertyName(productInfoById.getData().getPropertyName());
            orderGoods.setProductCode(productInfoById.getData().getProductCode());
            orderGoods.setBarCode(productInfoById.getData().getBarCode());
            orderGoods.setArtNo(productInfoById.getData().getArtNo());
            orderGoods.setPromotionId(request.getPromotionId());
            orderGoods.setPromotionType(11);
            long orderGoodsFlag = orderGoodsMapper.insert(orderGoods);
            if (orderGoodsFlag == 0) {
                return RestResult.error("9999", "创建订单商品明细失败!");
            }

            // 商品库存扣减
            commodityInventoryDeduction(orderGoods);

            // 4.操作日志
            OrderProcessLog orderProcessLog = new OrderProcessLog();
            orderProcessLog.setOrderNo(order.getOrderNo());
            orderProcessLog.setOperator(Long.parseLong(userId));
            orderProcessLog.setOperatorName(userName);
            orderProcessLog.setOperatorAction(OperatorActionEnum.USER_CREATE.getCode());
            orderProcessLog.setOperatorTime(currentTime);
            orderProcessLog.setOperatorLog("买家创建订单");
            orderProcessLog.setVersion(1);
            orderProcessLog.setCreator(Long.parseLong(userId));
            orderProcessLog.setCreateName(userName);
            orderProcessLog.setCreateTime(currentTime);
            orderProcessLog.setDeleteFlag(0);
            orderProcessLog.setDeptId(productInfoById.getData().getDeptId());
            orderProcessLogMapper.insert(orderProcessLog);
            return RestResult.success(orderParent.getParentOrderNo());
        }
        return RestResult.error("9999", "创建秒杀订单失败!");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<String> createJoinGroupOrder(CreateJoinGroupOrderRequest request) {
        log.info("创建拼团订单，request={}", JSON.toJSONString(request));

        // 获取用户id
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + request.getToken());
        if (StringUtils.isEmpty(userStr)) {
            return RestResult.error("4000", "登录失效");
        }
        Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
        String userId = userMap.get("id").toString();
        Object usernameStr = userMap.get("username");
        String userName = "";
        if (usernameStr != null) {
            userName = usernameStr.toString();
        }

        //查询商品基本信息
        ProductAfterInfoByIdResponse productInfoResponse = productListApi.queryProductInfoById(request.getGoodsId()).getData();
        // 校验开团商品
        LaunchOrJoinGrouponRequest joinGrouponRequest = new LaunchOrJoinGrouponRequest();
        joinGrouponRequest.setGroupCode(request.getGroupId());
//        joinGrouponRequest.setThirdProductCode(productInfoResponse.getCode());
        joinGrouponRequest.setMpId(request.getGoodsId());
        joinGrouponRequest.setLaunchFlag(request.getLaunchFlag());
        joinGrouponRequest.setThirdUserId(userId);
        joinGrouponRequest.setBuyNum(request.getBuyNum());
        joinGrouponRequest.setGrouponInstCode(request.getGroupInstCode());
        RestResult<LaunchOrJoinGrouponResponse> grouponResponseRestResult = grouponRestApi.launchOrJoinGrouponCheck(joinGrouponRequest);
        RestResult<ProductAfterInfoByIdResponse> productInfoById = productListApi.queryProductInfoById(request.getGoodsId());
        if (null != grouponResponseRestResult.getData() && !grouponResponseRestResult.getData().getLaunchOrJoinSuccess()) {
            orderMessagePush(Long.parseLong(userId), "您购买的" + productInfoById.getData().getChineseName() + "拼单失败,请重新拼单", 4);
            return RestResult.error("9999", grouponResponseRestResult.getMsg());
        }

        // 创建拼团订单
        if (null != productInfoById.getData()) {
            Date currentTime = new Date();
            // 1.创建父订单
            OrderParent orderParent = new OrderParent();
            BeanUtils.copyProperties(request, orderParent);
            orderParent.setOrderStatus(OrderStatusEnum.WAIT_PAY.getCode());
            orderParent.setParentOrderNo(SerialNoUtil.genParentOrderNo());
            orderParent.setVersion(1);
            orderParent.setBuyerId(Long.parseLong(userId));
            orderParent.setCreator(Long.parseLong(userId));
            orderParent.setCreateName(userName);
            orderParent.setCreateTime(currentTime);
            orderParent.setDeleteFlag(0);
            long orderParentFlag = orderParentMapper.insert(orderParent);
            if (orderParentFlag == 0) {
                return RestResult.error("9999", "创建订单失败!");
            }
//
//			// 使用优惠券
//			UseCouponRequest useCouponRequest = new UseCouponRequest();
//			useCouponRequest.setUserId(userId);
//			useCouponRequest.setCouponCode(request.getCouponCode());
//			useCouponRequest.setOrderCode(orderParent.getParentOrderNo());
//			RestResult<Boolean> booleanRestResult1 = couponRestApi.useCoupons(useCouponRequest);
//			if ("9999".equals(booleanRestResult1.getCode())) {
//				return RestResult.error("9999", booleanRestResult1.getMsg());
//			}

            // 2.创建子订单
            Order order = new Order();
            BeanUtils.copyProperties(request, order);
            order.setParentOrderNo(orderParent.getParentOrderNo());
            order.setOrderNo(SerialNoUtil.genOrderNo());
            order.setOrderStatus(OrderStatusEnum.WAIT_PAY.getCode());
            order.setMark(request.getMark());
            order.setVersion(1);
            order.setCreator(Long.parseLong(userId));
            order.setCreatorName(userName);
            order.setCreateTime(currentTime);
            order.setOrderType(0);
            order.setDeleteFlag(true);
            order.setBuyerId(Long.parseLong(userId));
            order.setDeptId(productInfoById.getData().getDeptId());
            long orderFlag = orderMapper.insert(order);
            if (orderFlag == 0) {
                return RestResult.error("9999", "创建订单失败!");
            }

            // 3.创建订单商品明细
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderNo(order.getOrderNo());
            orderGoods.setGoodsId(request.getGoodsId());
            orderGoods.setGoodsName(productInfoById.getData().getChineseName());
            orderGoods.setGoodsImgUrl(productInfoById.getData().getPictureUrl());
            orderGoods.setGoodsType(productInfoById.getData().getType());
            orderGoods.setGoodsNum(1);
            orderGoods.setWaitTransferDeliverNum(1);
            orderGoods.setSaleUnitPrice(productInfoById.getData().getMarketPrice());
            orderGoods.setDiscountUnitPrice(request.getDiscountTotalAmount());
            orderGoods.setBuyUnitPrice(request.getBuyTotalAmount());
            orderGoods.setExpressUnitFee(request.getExpressTotalFee());
            orderGoods.setActualPayTotalAmount(request.getActualPayTotalAmount());
            orderGoods.setMark(request.getMark());
            orderGoods.setVersion(1);
            orderGoods.setCreator(Long.parseLong(userId));
            orderGoods.setCreateName(userName);
            orderGoods.setCreateTime(currentTime);
            orderGoods.setDeleteFlag(0);
            orderGoods.setDeptId(productInfoById.getData().getDeptId());
            orderGoods.setUnitName(productInfoById.getData().getUnitName());
            orderGoods.setPropertyName(productInfoById.getData().getPropertyName());
            orderGoods.setProductCode(productInfoById.getData().getProductCode());
            orderGoods.setBarCode(productInfoById.getData().getBarCode());
            orderGoods.setArtNo(productInfoById.getData().getArtNo());
            long orderGoodsFlag = orderGoodsMapper.insert(orderGoods);
            if (orderGoodsFlag == 0) {
                return RestResult.error("9999", "创建订单商品明细失败!");
            }

            // 商品库存扣减
            commodityInventoryDeduction(orderGoods);

            // 4.操作日志
            OrderProcessLog orderProcessLog = new OrderProcessLog();
            orderProcessLog.setOrderNo(order.getOrderNo());
            orderProcessLog.setOperator(Long.parseLong(userId));
            orderProcessLog.setOperatorName(userName);
            orderProcessLog.setOperatorAction(OperatorActionEnum.USER_CREATE.getCode());
            orderProcessLog.setOperatorTime(currentTime);
            orderProcessLog.setOperatorLog("买家创建订单");
            orderProcessLog.setVersion(1);
            orderProcessLog.setCreator(Long.parseLong(userId));
            orderProcessLog.setCreateName(userName);
            orderProcessLog.setCreateTime(currentTime);
            orderProcessLog.setDeleteFlag(0);
            orderProcessLog.setDeptId(productInfoById.getData().getDeptId());
            orderProcessLogMapper.insert(orderProcessLog);

            // 订单付款消息推送
            orderMessagePush(Long.parseLong(userId), "恭喜您购买的" + orderGoods.getGoodsName() + "拼单成功,请及时完成付款", 3);
            joinGrouponRequest.setThirdOrderCode(order.getOrderNo());
            RestResult<LaunchOrJoinGrouponResponse> grouponResponseRestResult1 = grouponRestApi.launchOrJoinGroupon(joinGrouponRequest);
            return RestResult.success(orderParent.getParentOrderNo());
        }
        return RestResult.error("9999", "创建拼团订单失败!");
    }

    @Override
    public RestResult<String> pay(FrontPayOrderRequest request) {
        log.info("买家付款，request={}", JSON.toJSONString(request));
        OperateModel operate = new OperateModel(OperatorActionEnum.USER_PAY, request.getSerialNo());
        operate.setOperatorLog("买家付款");
        RestResult<String> restResult = executeOperate(operate, new BaseService.TemplateService<String, ParentOrderModel>() {

            @Override
            public ParentOrderModel init() {
                if (!SerialNoUtil.isParentOrderNo(request.getParentOrderNo())) {
                    log.info("必须传入父订单号, request={}", JSON.toJSONString(request));
                    throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "必须传入父订单号");
                }
                ParentOrderModel parentOrderModel = new ParentOrderModel();
                parentOrderModel.setParentOrderNo(request.getParentOrderNo());
                return parentOrderModel;
            }

            @Override
            public String process(ParentOrderModel model) {
                //补全操作者信息
                if (null != model && null != model.getOrderModelList()
                        && !model.getOrderModelList().isEmpty() && null != model.getOrderModelList().get(0).getBuyerModel()) {
                    operate.setOperator(model.getOrderModelList().get(0).getBuyerModel().getBuyerId());
                    operate.setOperatorName(model.getOrderModelList().get(0).getBuyerModel().getBuyerUsername());
                }

                //直接到已经支付状态
                if (!OrderStatusEnum.WAIT_PAY.getCode().equals(model.getOrderStatus())) {
                    log.error("该状态" + model.getOrderStatus() + "不允许付款, request={}", JSON.toJSONString(request));
                    throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + model.getOrderStatus() + "不允许付款");
                }

                List<OrderExamine> orderExamineList = orderExamineMapper.query(new OrderExamine() {{
                    setDeleteFlag(0);
                    //TODO 暂时订单备注设置
                    setVariableName(6L);
                }});
                model.setOrderStatus(OrderStatusEnum.ALREADY_PAY.getCode());
                List<OrderModel> orderModelList = model.getOrderModelList();
                for (OrderModel orderModel : orderModelList) {
                    if (!OrderStatusEnum.WAIT_PAY.getCode().equals(orderModel.getOrderStatus())) {
                        log.error("该状态" + orderModel.getOrderStatus() + "不允许付款, request={}", JSON.toJSONString(request));
                        throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + orderModel.getOrderStatus() + "不允许付款");
                    }

                    if (CollectionUtils.isNotEmpty(orderExamineList)) {
                        //订单备注不为空的时候自动审核通过
                        if (StringUtils.isNotEmpty(orderModel.getMark())) {
                            orderModel.setOrderStatus(OrderStatusEnum.WAIT_SHIP.getCode());
                        } else {
                            orderModel.setOrderStatus(OrderStatusEnum.ALREADY_PAY.getCode());
                        }
                    }
                }

                return model.getParentOrderNo();
            }
        });

        // 支付成功 积分,成长值,消息
        if (OrderEnum.SUCCESS.getCode().equals(restResult.getCode())) {
            OrderParent orderParent = orderParentMapper.queryByPrimaryKey(request.getParentOrderNo());

            // 下单赠送积分
            MemberIntegralRestRequest integralRestRequest = new MemberIntegralRestRequest();
            integralRestRequest.setUserId(orderParent.getBuyerId());
            integralRestRequest.setChangeTypes(1);
            integralRestRequest.setObtainMode(1);
            integralRestRequest.setOrderId(orderParent.getId());
            integralRestRequest.setPlaceOrderAmount(orderParent.getActualPayTotalAmount());
            mememberActionApi.addMemberIntegralInfoNew(integralRestRequest);

            // todo 暂时未添加是否积分抵扣判断
            // 消费抵现金扣减积分
            //			MemberIntegralRestRequest integralRestRequest1 = new MemberIntegralRestRequest();
            //			integralRestRequest1.setUserId(orderParent.getBuyerId());
            //			integralRestRequest1.setChangeTypes(2);
            //			integralRestRequest1.setObtainMode(1);
            //			integralRestRequest1.setOrderId(orderParent.getId());
            //			integralRestRequest1.setPlaceOrderAmount(orderParent.getActualPayTotalAmount());
            //			mememberActionApi.addMemberIntegralInfoNew(integralRestRequest1);

            // 下单赠送成长值
            ObtainOrConsumptionGrowthRequest obtainOrConsumptionGrowthRequest = new ObtainOrConsumptionGrowthRequest();
            obtainOrConsumptionGrowthRequest.setMemberId(String.valueOf(orderParent.getBuyerId()));
            obtainOrConsumptionGrowthRequest.setObtainMode("1");
            obtainOrConsumptionGrowthRequest.setActionType(3L);
            obtainOrConsumptionGrowthRequest.setOrderMoney(orderParent.getActualPayTotalAmount());
            memberGrowthOperationApi.obtainOrConsumptionGrowth(obtainOrConsumptionGrowthRequest);

            // todo 暂时未添加是否消费抵现金成长值判断
            // 消费抵现金成长值
            //			ObtainOrConsumptionGrowthRequest obtainOrConsumptionGrowthRequest1 = new ObtainOrConsumptionGrowthRequest();
            //			obtainOrConsumptionGrowthRequest1.setMemberId(String.valueOf(orderParent.getBuyerId()));
            //			obtainOrConsumptionGrowthRequest1.setObtainMode("1");
            //			obtainOrConsumptionGrowthRequest1.setActionType(2L);
            //			obtainOrConsumptionGrowthRequest1.setOrderMoney(orderParent.getActualPayTotalAmount());
            //			memberGrowthOperationApi.obtainOrConsumptionGrowth(obtainOrConsumptionGrowthRequest1);
            if (orderParent.getParentOrderNo() != null) {
                List<Order> orders = orderMapper.query(new Order() {{
                    setParentOrderNo(orderParent.getParentOrderNo());
                }});
                if (CollectionUtils.isNotEmpty(orders)) {
                    PostPayGroupInstDetailRequest postPayGroupInstDetailRequest = new PostPayGroupInstDetailRequest();
                    postPayGroupInstDetailRequest.setThirdOrderCode(orders.get(0).getOrderNo());
                    postPayGroupInstDetailRequest.setThirdUserId(String.valueOf(orderParent.getBuyerId()));
                    getGrouponRestApi.postPayGroupInstDetail(postPayGroupInstDetailRequest);
                }
            }

        }
        return restResult;
    }

    @Override
    public RestResult<String> close(FrontCloseOrderRequest request) {
        log.info("关闭订单，request={}", JSON.toJSONString(request));

        OperateModel operate = new OperateModel(OperatorActionEnum.CANCEL_ORDER, request.getSerialNo());
        operate.setOperatorLog("买家取消订单");
        return executeOperate(operate, new BaseService.TemplateService<String, ParentOrderModel>() {

            @Override
            public ParentOrderModel init() {
                if (!SerialNoUtil.isParentOrderNo(request.getParentOrderNo())) {
                    log.info("必须传入父订单号, request={}", JSON.toJSONString(request));
                    throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "必须传入父订单号");
                }
                ParentOrderModel parentOrderModel = new ParentOrderModel();
                parentOrderModel.setParentOrderNo(request.getParentOrderNo());
                return parentOrderModel;
            }

            @Override
            public String process(ParentOrderModel model) {
                // 补全操作者信息
                if (null != model && null != model.getOrderModelList() && !model.getOrderModelList().isEmpty() && null != model.getOrderModelList().get(0).getBuyerModel()) {
                    operate.setOperator(model.getOrderModelList().get(0).getBuyerModel().getBuyerId());
                    operate.setOperatorName(model.getOrderModelList().get(0).getBuyerModel().getBuyerUsername());
                }


                if (null!=request.getOperateType() && request.getOperateType().equals(1)){
                    // 直接到已经支付状态
                    if (!OrderStatusEnum.CLOSED.getCode().equals(model.getOrderStatus())) {
                        log.error("该状态" + model.getOrderStatus() + "不允许删除订单, request={}", JSON.toJSONString(request));
                        throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + model.getOrderStatus() + "不允许删除订单");
                    }
                    model.setOrderStatus(OrderStatusEnum.DELETE.getCode());
                }else {
                    // 直接到已经支付状态
                    if (!OrderStatusEnum.WAIT_PAY.getCode().equals(model.getOrderStatus())) {
                        log.error("该状态" + model.getOrderStatus() + "不允许取消订单, request={}", JSON.toJSONString(request));
                        throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + model.getOrderStatus() + "不允许取消订单");
                    }
                    model.setOrderStatus(OrderStatusEnum.CLOSED.getCode());
                }
                List<OrderModel> orderModelList = model.getOrderModelList();
                for (OrderModel orderModel : orderModelList) {

                    if (null!=request.getOperateType() &&request.getOperateType().equals(1)){
                        if (!OrderStatusEnum.CLOSED.getCode().equals(orderModel.getOrderStatus())) {
                            log.error("该状态" + orderModel.getOrderStatus() + "不允许删除订单, request={}", JSON.toJSONString(request));
                            throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + orderModel.getOrderStatus() + "不允许删除订单");
                        }
                        orderModel.setOrderStatus(OrderStatusEnum.DELETE.getCode());
                    }else {
                        if (!OrderStatusEnum.WAIT_PAY.getCode().equals(orderModel.getOrderStatus())) {
                            log.error("该状态" + orderModel.getOrderStatus() + "不允许取消订单, request={}", JSON.toJSONString(request));
                            throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + orderModel.getOrderStatus() + "不允许取消订单");
                        }
                        orderModel.setOrderStatus(OrderStatusEnum.CLOSED.getCode());
                    }
                }

                return model.getParentOrderNo();
            }
        });
    }

    @Override
    public RestResult<String> sendGoods(SendGoodsRequest request) {
        log.info("发货，request={}", JSON.toJSONString(request));
        OperateModel operate = new OperateModel(OperatorActionEnum.SEND_GOODS, request.getSerialNo());
        operate.setOperator(request.getOperator());
        operate.setOperatorName(request.getOperateName());
        operate.setOperatorLog("卖家发货");
        return executeOperate(operate, new TemplateService<String, OrderDeliverModel>() {
            @Override
            public OrderDeliverModel init() {
                OrderDeliverModel model = new OrderDeliverModel();
                model.setDeliverNo(request.getDeliverNo());
                return model;
            }

            @Override
            public String process(OrderDeliverModel model) {
                if (!OrderStatusEnum.WAIT_SHIP.getCode().equals(model.getOrderStatus())) {
                    log.error("该状态" + model.getOrderStatus() + "不允许发货, request={}", JSON.toJSONString(request));
                    throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + model.getOrderStatus() + "不允许发货");
                }

                //设置收货人信息
                BeanUtils.copyProperties(request, model);

                //更改交货单状态
                model.setOrderStatus(OrderStatusEnum.ALREADY_SHIP.getCode());

                //记录包裹信息
                List<OrderBaleModel> orderBaleModelList = new ArrayList<>();
                List<BaleInfo> baleInfoList = request.getBaleInfoList();
                if (null != baleInfoList && !baleInfoList.isEmpty()) {
                    for (BaleInfo baleInfo : baleInfoList) {
                        OrderBaleModel orderBaleModel = new OrderBaleModel();
                        BeanUtils.copyProperties(model.getSellerModel(), orderBaleModel);
                        orderBaleModel.setDeliverNo(model.getDeliverNo());
                        orderBaleModel.setOrderNo(model.getOrderNo());
                        orderBaleModel.setBaleNo(SerialNoUtil.genBaleNo());
                        orderBaleModel.setOrderStatus(OrderStatusEnum.ALREADY_SHIP.getCode());
                        orderBaleModel.setDistributor(baleInfo.getDistributor());
                        orderBaleModel.setExpressNo(baleInfo.getExpressNo());

                        List<OrderBaleDetailModel> orderBaleDetailModelList = new ArrayList<>();

                        // 补全商品信息，如果前端没传的话
                        if (null == baleInfo.getBaleDetailInfoList() || baleInfo.getBaleDetailInfoList().isEmpty()) {
                            List<BaleDetailInfo> baleDetailInfoList = new ArrayList<>();
                            List<OrderDeliverDetailModel> modelOrderDeliverDetailModelList = model.getOrderDeliverDetailModelList();
                            if (null != modelOrderDeliverDetailModelList && !modelOrderDeliverDetailModelList.isEmpty()) {
                                for (OrderDeliverDetailModel deliverDetailModel : modelOrderDeliverDetailModelList) {
                                    orderMessagePush(model.getBuyerId(), "您购买的" + deliverDetailModel.getGoodsName() + "商家已发货,请留意到货信息", 2);
                                    BaleDetailInfo baleDetailInfo = new BaleDetailInfo();
                                    BeanUtils.copyProperties(deliverDetailModel, baleDetailInfo);
                                    baleDetailInfoList.add(baleDetailInfo);
                                }
                                baleInfo.setBaleDetailInfoList(baleDetailInfoList);
                            }
                        }
                        if (null != baleInfo.getBaleDetailInfoList() && !baleInfo.getBaleDetailInfoList().isEmpty()) {
                            for (BaleDetailInfo baleDetailInfo : baleInfo.getBaleDetailInfoList()) {
                                orderMessagePush(model.getBuyerId(), "您购买的" + baleDetailInfo.getGoodsName() + "商家已发货,请留意到货信息", 2);
                                OrderBaleDetailModel orderBaleDetailModel = new OrderBaleDetailModel();
                                BeanUtils.copyProperties(baleDetailInfo, orderBaleDetailModel);
                                orderBaleDetailModelList.add(orderBaleDetailModel);
                            }
                            orderBaleModel.setOrderBaleDetailModelList(orderBaleDetailModelList);
                        }
                        orderBaleModelList.add(orderBaleModel);
                    }
                    model.setOrderBaleModelList(orderBaleModelList);
                }

                //默认插入一条物流信息
                OrderBaleDelivery orderBaleDelivery = new OrderBaleDelivery();
                orderBaleDelivery.setExpressNo(request.getBaleInfoList().get(0).getExpressNo());
                List<OrderBaleDelivery> orderBaleDeliveryList = orderBaleDeliveryService.query(orderBaleDelivery);
                if (CollectionUtils.isEmpty(orderBaleDeliveryList)) {
                    orderBaleDelivery.setOrderNo(model.getOrderNo());
                    orderBaleDelivery.setDeliveryCompanyId(Long.valueOf(request.getBaleInfoList().get(0).getDistributor()));
                    //物流备注暂时写死
                    orderBaleDelivery.setRemark("【北京市】 快件已在 【北京太阳宫】 签收, 签收人: 前台, 如有疑问请电联:13370150897 / 010-67443169, 您的快递已经妥投。风里来雨里去, 只为客官您满意。上有老下有小, 赏个好评好不好？【请在评价快递员处帮忙点亮五颗星星哦~】");
                    orderBaleDeliveryService.insert(orderBaleDelivery);
                }

                return model.getDeliverNo();
            }

        });
    }

    @Override
    public RestResult<String> handDeliver(HandDeliverRequest handDeliverRequest) {
        log.info("手动转交货单，request={}", JSON.toJSONString(handDeliverRequest));
        OperateModel operate = new OperateModel(OperatorActionEnum.DELIVER, handDeliverRequest.getSerialNo());
        return executeOperate(operate, new TemplateService<String, OrderModel>() {

            @Override
            public OrderModel init() {
                OrderModel orderModel = new OrderModel();
                orderModel.setOrderNo(handDeliverRequest.getOrderNo());
                return orderModel;
            }

            @Override
            public String process(OrderModel model) {
                OrderDeliverModel orderDeliverModel = new OrderDeliverModel();
                orderDeliverModel.setDeliverNo(IDUtils.GenerateBillNo());
                orderDeliverModel.setOrderStatus(DeliverStatusEnum.WAIT_SHIP.getCode());
                List<HandDeliverRequest.HandDeliver> handDeliverList = handDeliverRequest.getHandDeliverList();
                for (HandDeliverRequest.HandDeliver handDeliver : handDeliverList) {
                    OrderGoodsModel orderGoodsModel = model.getOrderGoodsModelById(handDeliver.getId());
                    if (null == orderGoodsModel) {
                        log.info("商品记录不存在，orderGoodsId={}", handDeliver.getId());
                        throw new OrderException(OrderEnum.DATA_EXECEPTION, "商品记录不存在");
                    }
                    if (!orderGoodsModel.getWaitTransferDeliverNum().equals(handDeliver.getWaitTransferDeliverNum())) {
                        log.info("数据已经发生变化，请刷新，orderGoodsId={}", handDeliver.getId());
                        throw new OrderException(OrderEnum.DATA_VERSION_EXECEPTION, "数据已经发生变化，请刷新");
                    }
                    if (orderGoodsModel.getWaitTransferDeliverNum() < handDeliver.getTransferDeliverNum()) {
                        log.info("待转交货单数量不足，orderGoodsId={}", handDeliver.getId());
                        throw new OrderException(OrderEnum.DATA_EXECEPTION, "待转交货单数量不足");
                    }

                    //商品的数量更新
                    orderGoodsModel.setWaitTransferDeliverNum(orderGoodsModel.getWaitTransferDeliverNum() - handDeliver.getTransferDeliverNum());
                    orderGoodsModel.setAlreadyTransferDeliverNum(orderGoodsModel.getAlreadyTransferDeliverNum() + handDeliver.getTransferDeliverNum());

                    //交货单明细
                    OrderDeliverModel.OrderDeliverDetailModel orderDeliverDetailModel = new OrderDeliverModel.OrderDeliverDetailModel();
                    orderDeliverDetailModel.setGoodsId(orderGoodsModel.getGoodsId());
                    orderDeliverDetailModel.setGoodsName(orderGoodsModel.getGoodsName());
                    orderDeliverDetailModel.setGoodsNum(handDeliver.getTransferDeliverNum());
                    orderDeliverModel.getOrderDeliverDetailModelList().add(orderDeliverDetailModel);
                }
                model.getOrderDeliverModelList().add(orderDeliverModel);

                return model.getOrderDeliverModelList().get(0).getDeliverNo();
            }
        });
    }

    @Override
    public RestResult<String> confirmShip(FrontConfirmShipOrderRequest request) {
        log.info("确认收货，request={}", JSON.toJSONString(request));
        OperateModel operate = new OperateModel(OperatorActionEnum.CONFIRM_RECEIPT, request.getSerialNo());
        operate.setOperatorLog("买家确认收货");
        if (SerialNoUtil.isParentOrderNo(request.getOrderNo())) {
            // 父订单号
            return executeOperate(operate, new BaseService.TemplateService<String, ParentOrderModel>() {

                @Override
                public ParentOrderModel init() {
                    if (!SerialNoUtil.isParentOrderNo(request.getOrderNo())) {
                        log.info("必须传入订单号或父订单号, request={}", JSON.toJSONString(request));
                        throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "必须传入订单号或父订单号");
                    }
                    ParentOrderModel parentOrderModel = new ParentOrderModel();
                    parentOrderModel.setParentOrderNo(request.getOrderNo());
                    return parentOrderModel;
                }

                @Override
                public String process(ParentOrderModel model) {
                    // 补全操作者信息
                    if (null != model && null != model.getOrderModelList() &&
                            !model.getOrderModelList().isEmpty() &&
                            null != model.getOrderModelList().get(0).getBuyerModel()) {
                        operate.setOperator(model.getOrderModelList().get(0).getBuyerModel().getBuyerId());
                        operate.setOperatorName(model.getOrderModelList().get(0).getBuyerModel().getBuyerUsername());
                    }

                    // 直接到已经支付状态
                    if (!OrderStatusEnum.ALREADY_SHIP.getCode().equals(model.getOrderStatus())) {
                        log.error("该状态" + model.getOrderStatus() + "不允许确认收货, request={}", JSON.toJSONString(request));
                        throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + model.getOrderStatus() + "不允许确认收货");
                    }

                    // 原确认收货状态现改为待评价状态
                    model.setOrderStatus(OrderStatusEnum.WAIT_REVIEW.getCode());
                    List<OrderModel> orderModelList = model.getOrderModelList();
                    for (OrderModel orderModel : orderModelList) {
                        if (!OrderStatusEnum.ALREADY_SHIP.getCode().equals(orderModel.getOrderStatus())) {
                            log.error("该状态" + orderModel.getOrderStatus() + "不允许确认收货, request={}", JSON.toJSONString(request));
                            throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + orderModel.getOrderStatus() + "不允许确认收货");
                        }
                        orderModel.setOrderStatus(OrderStatusEnum.WAIT_REVIEW.getCode());
                    }
                    return model.getParentOrderNo();
                }

            });
        } else {
            // 子订单号
            return executeOperate(operate, new BaseService.TemplateService<String, OrderModel>() {

                @Override
                public OrderModel init() {
                    if (!SerialNoUtil.isOrderNo(request.getOrderNo())) {
                        log.info("必须传入订单号或父订单号, request={}", JSON.toJSONString(request));
                        throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "必须传入订单号或父订单号");
                    }
                    OrderModel orderModel = new OrderModel();
                    orderModel.setOrderNo(request.getOrderNo());
                    return orderModel;
                }

                @Override
                public String process(OrderModel model) {
                    //补全操作者信息
                    operate.setOperator(model.getBuyerModel().getBuyerId());
                    operate.setOperatorName(model.getBuyerModel().getBuyerUsername());
                    //直接到已经支付状态
                    if (!OrderStatusEnum.ALREADY_SHIP.getCode().equals(model.getOrderStatus())) {
                        log.error("该状态" + model.getOrderStatus() + "不允许确认收货, request={}", JSON.toJSONString(request));
                        throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + model.getOrderStatus() + "不允许确认收货");
                    }
                    model.setOrderStatus(OrderStatusEnum.WAIT_REVIEW.getCode());
                    return model.getParentOrderNo();
                }
            });
        }
    }

    @Override
    public RestResult<String> audit(OrderAuditRequest request) {
        log.info("审核，request={}", JSON.toJSONString(request));
        OperateModel operate = new OperateModel(OperatorActionEnum.AUDIT, request.getSerialNo());
        operate.setOperator(request.getOperator());
        operate.setOperatorName(request.getOperateName());
        operate.setOperatorLog("商家审核");
        return executeOperate(operate, new BaseService.TemplateService<String, OrderModel>() {

            @Override
            public OrderModel init() {
                OrderModel orderModel = new OrderModel();
                orderModel.setOrderNo(request.getOrderNo());
                return orderModel;
            }

            @Override
            public String process(OrderModel model) {
                //直接到已经支付状态
                if (!OrderStatusEnum.ALREADY_PAY.getCode().equals(model.getOrderStatus())) {
                    log.error("该状态" + model.getOrderStatus() + "不允许审核, request={}", JSON.toJSONString(request));
                    throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "该状态" + model.getOrderStatus() + "不允许审核");
                }
                OrderParent orderParent = new OrderParent();
                orderParent.setParentOrderNo(model.getParentOrderNo());
                List<OrderParent> orderParentList = orderParentMapper.query(orderParent);
                if (request.getAuditStatus() == 1) {
                    //分配交货单
                    List<OrderGoodsModel> orderGoodsModelList = model.getOrderGoodsModelList();
                    List<OrderDeliverModel> orderDeliverModelList = new ArrayList<>();
                    if (null != orderGoodsModelList && !orderGoodsModelList.isEmpty()) {
                        for (OrderGoodsModel orderGoodsModel : orderGoodsModelList) {
                            OrderDeliverModel orderDeliverModel = new OrderDeliverModel();
                            BeanUtils.copyProperties(orderGoodsModel, orderDeliverModel, "id");
                            //添加买家和收货人信息
                            BeanUtils.copyProperties(orderParentList.get(0), orderDeliverModel, "id");
                            orderDeliverModel.setBuyTime(model.getBuyTime());
                            orderDeliverModel.setBuyerId(model.getBuyerModel().getBuyerId());
                            orderDeliverModel.setBuyerUsername(model.getBuyerModel().getBuyerUsername());
                            orderDeliverModel.setBuyerRealname(model.getBuyerModel().getBuyerRealname());
                            orderDeliverModel.setDeliverNo(SerialNoUtil.genDeliveNo());
                            orderDeliverModel.setSellerModel(model.getSellerModel());
                            orderDeliverModel.setOrderNo(model.getOrderNo());
                            orderDeliverModel.setOrderStatus(OrderStatusEnum.WAIT_SHIP.getCode());
                            List<OrderDeliverModel.OrderDeliverDetailModel> orderDeliverDetailModelList = new ArrayList<>();
                            OrderDeliverModel.OrderDeliverDetailModel orderDeliverDetailModel = new OrderDeliverModel.OrderDeliverDetailModel();
                            BeanUtils.copyProperties(orderGoodsModel, orderDeliverDetailModel, "id");
                            orderDeliverDetailModelList.add(orderDeliverDetailModel);
                            orderDeliverModel.setOrderDeliverDetailModelList(orderDeliverDetailModelList);
                            orderDeliverModelList.add(orderDeliverModel);
                            model.setOrderDeliverModelList(orderDeliverModelList);
                            RestResult<ProductAfterInfoByIdResponse> responseRestResult = productListApi.queryProductInfoById(orderGoodsModel.getGoodsId());
                            if (responseRestResult.getData() != null &&
                                    responseRestResult.getData().getType() != null &&
                                    (responseRestResult.getData().getType() == 3 || responseRestResult.getData().getType() == 4)) {
                                break;
                            }
                        }
                    }
                    model.setOrderStatus(OrderStatusEnum.WAIT_SHIP.getCode());
                } else {
                    //退款给用户，并关闭订单
                    model.setOrderStatus(OrderStatusEnum.CLOSED.getCode());
                }
                return model.getOrderNo();
            }
        });
    }

    @Override
    public RestResult<String> modifyStatus(ModifyOrderStatusRequest request) {
        log.info("修改订单状态，request={}", JSON.toJSONString(request));
        OperateModel operate = new OperateModel(OperatorActionEnum.MODIFY_ORDER_STATUS, request.getSerialNo());
        operate.setOperator(request.getOperator());
        operate.setOperatorName(request.getOperateName());
        operate.setOperatorLog(request.getOperatorLog());
        return executeOperate(operate, new BaseService.TemplateService<String, OrderModel>() {

            @Override
            public OrderModel init() {
                //直接到已经支付状态
                if (!OrderStatusEnum.REFUND.getCode().equals(request.getOrderStatus())
                        && !OrderStatusEnum.FINISH.getCode().equals(request.getOrderStatus())) {
                    log.error("不支持该状态的更改, request={}", JSON.toJSONString(request));
                    throw new OrderException(OrderEnum.REQUEST_PARAMETER_EXECEPTION, "不支持该状态的更改");
                }
                OrderModel orderModel = new OrderModel();
                orderModel.setOrderNo(request.getOrderNo());
                return orderModel;
            }

            @Override
            public String process(OrderModel model) {
                model.setOrderStatus(request.getOrderStatus());
                return model.getOrderNo();
            }
        });
    }

    @Override
    public Map queryOrderInfoOrList(ApiOrder apiOrder) {
        Map<String, Object> map = new HashMap<>();
        log.info("微众==客服查询订单信息请求参数=============>>:{}", JSONObject.toJSONString(apiOrder));
        if (apiOrder == null || StringUtils.isEmpty(apiOrder.getQuery_type())) {
            map.put("ret_code", "-1");
            map.put("ret_msg", "请求参数错误");
            map.put("ret_data", new Object());
            return map;
        }
        map.put("ret_code", "25350000");
        map.put("ret_msg", "成功");

        //查询方式，O-订单，L-查询订单列表
        if (StringUtils.equals("O", apiOrder.getQuery_type())) {
            if (StringUtils.isEmpty(apiOrder.getOrder_id())) {
                map.put("ret_code", "-1");
                map.put("ret_msg", "订单号不能为空");
                map.put("ret_data", new Object());
                return map;
            }
            List<Order> orders = orderMapper.query(new Order() {{
                setOrderNo(apiOrder.getOrder_id());
                setSerialNo(apiOrder.getBiz_no());
            }});
            if (CollectionUtils.isEmpty(orders)) {
                log.info("订单查询为空直接返回");
                map.put("ret_data", new Object());
                return map;
            }
            OrderItemResponse orderItemResponse = this.encapsulatedObjectMethod(orders.get(0));
            map.put("ret_data", orderItemResponse);
            log.info("微众单个对象返回=================>>:{}", JSONObject.toJSONString(orderItemResponse));
        } else if (StringUtils.equals("L", apiOrder.getQuery_type())) {
            List<Order> orders = orderMapper.query(new Order());
            List<OrderItemResponse> orderItemResponses = new ArrayList<>();
            orders.forEach(order -> {
                if(41!=order.getOrderType() && 11!=order.getOrderType()){
                    OrderItemResponse orderItemResponse = this.encapsulatedObjectMethod(order);
                    orderItemResponses.add(orderItemResponse);
                }
            });
            if (CollectionUtils.isNotEmpty(orderItemResponses)) {
                OrderItemListResponse orderItemListResponse = new OrderItemListResponse();
                orderItemListResponse.setCreate_time(orderItemResponses.get(0).getCreate_time());
                orderItemListResponse.setOrder_id(orderItemResponses.get(0).getOrder_id());
                orderItemListResponse.setProd_name(orderItemResponses.get(0).getOrderItemGoodsList().get(0).getProd_name());
                orderItemListResponse.setOrderItemList(orderItemResponses);
                map.put("ret_data", orderItemListResponse);
            } else {
                map.put("ret_data", new Object());
            }
        }
        return map;
    }

    /**
     * description: 订单消息推送接口
     *
     * @author: jackHe
     * @time: 2020/8/25 14:30
     */
    private void orderMessagePush(long buyerId, String title, int type) {
        MeinformationRequest meinformationRequest = new MeinformationRequest();
        meinformationRequest.setMemberId(buyerId);
        meinformationRequest.setType(type);
        meinformationRequest.setTitle(title);
        meinformationRequest.setCategory(1);
        memberInformationApi.insertMemberInformation(meinformationRequest);
    }

    /**
     * description: 商品库存扣减
     *
     * @author: jackHe
     * @time: 2020/8/27 16:09
     */
    private void commodityInventoryDeduction(OrderGoods orderGoods) {
        MStoreFrozenRequest mStoreFrozenRequest = new MStoreFrozenRequest();
        mStoreFrozenRequest.setApplyNum(Long.valueOf(orderGoods.getGoodsNum()));
        mStoreFrozenRequest.setCode(orderGoods.getOrderNo());
        mStoreFrozenRequest.setProductId(orderGoods.getGoodsId());
        mStoreFrozenRequest.setFrozenFlag(true);
        productListApi.frozenStock(mStoreFrozenRequest);
    }

    private OrderItemResponse encapsulatedObjectMethod(Order order) {
        OrderItemResponse orderItemResponse = new OrderItemResponse();
        //查询用户信息
        RestResult<MememberUserResponse> mememberUserResponseRestResult = mememberApi.queryMemberUserInfo(order.getBuyerId());
        if (RestResult.checkIsSuccess(mememberUserResponseRestResult)) {
            orderItemResponse.setWechat_openid(mememberUserResponseRestResult.getData().getUnionId());
            orderItemResponse.setWechat_unionid(mememberUserResponseRestResult.getData().getUnionId());
        }
        orderItemResponse.setOrder_id(order.getOrderNo());
        orderItemResponse.setAmount(order.getBuyTotalAmount());
        orderItemResponse.setCoupon_cut(order.getDiscountTotalAmount());
        orderItemResponse.setCreate_time(order.getBuyTime());
        orderItemResponse.setOrder_type(OrderTypeEnum.getByCode(order.getOrderType() == null ? 0 : order.getOrderType()).getMessage());
        orderItemResponse.setPay_type(PayTypeEnum.getByCode(order.getPayment() == null ? 1 : order.getPayment()).getMessage());
        orderItemResponse.setShip_type("0");
        orderItemResponse.setOrder_type(OrderStatusEnum.getByCode(order.getOrderStatus()).getMessage());
        orderItemResponse.setRemark(order.getMark());
        orderItemResponse.setReal_amount(order.getBuyTotalAmount());
        //查询父订单
        OrderParent orderParent = orderParentMapper.queryByPrimaryKey(order.getParentOrderNo());
        if (orderParent != null) {
            orderItemResponse.setCity(orderParent.getReceiverCityName());
            orderItemResponse.setProvince(orderParent.getReceiverProvinceName());
            orderItemResponse.setRegion(orderParent.getReceiverRegionName());
            orderItemResponse.setDetail_address(orderParent.getReceiverAddress());
            orderItemResponse.setPhone_no(orderParent.getReceiverPhone());
            orderItemResponse.setUser_name(orderParent.getReceiverName());
            orderItemResponse.setTrans_time(orderParent.getUpdateTime());

        }
        //查询商品数据
        List<OrderGoods> orderGoodsList = orderGoodsMapper.query(new OrderGoods() {{
            setOrderNo(order.getOrderNo());
            setDeleteFlag(0);
        }});
        List<OrderItemGoodsResponse> orderItemGoodsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderGoodsList)) {
            orderGoodsList.forEach(orderGoods -> {
                OrderItemGoodsResponse orderItemGoodsResponse = new OrderItemGoodsResponse();
                orderItemGoodsResponse.setBuy_num(orderGoods.getGoodsNum());
                orderItemGoodsResponse.setCurrent_price(orderGoods.getSaleUnitPrice());
                orderItemGoodsResponse.setOrigin_price(orderGoods.getSaleUnitPrice());
                orderItemGoodsResponse.setProd_code(orderGoods.getProductCode());
                orderItemGoodsResponse.setProd_name(orderGoods.getGoodsName());
                orderItemGoodsList.add(orderItemGoodsResponse);
            });
        }
        orderItemResponse.setOrderItemGoodsList(orderItemGoodsList);
        //包裹信息
        List<OrderBale> orderBaleList = orderBaleMapper.query(new OrderBale() {{
            setOrderNo(order.getOrderNo());
        }});
        if (CollectionUtils.isNotEmpty(orderBaleList)) {
            OrderBale orderBale = orderBaleList.get(0);

            orderItemResponse.setLogistics_id(orderBale.getExpressNo());
            orderItemResponse.setLogistics_type(orderBale.getDistributorName());

            ExpressResponse express = new ExpressResponse();
            express.setEBusinessID(orderBale.getReceiverName());
            express.setShipperCode(orderBale.getExpressNo());
            express.setSuccess(true);
            express.setState(orderBale.getOrderStatus().toString());

            List<OrderBaleDelivery> orderBaleDeliveryList = orderBaleDeliveryMapper.query(new OrderBaleDelivery() {{
                setBaleNo(orderBale.getBaleNo());
            }});
            List<TracesResponse> traces = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(orderBaleDeliveryList)) {
                orderBaleDeliveryList.forEach(orderBaleDelivery -> {
                    TracesResponse tracesResponse = new TracesResponse();
                    tracesResponse.setAcceptStation(orderBaleDelivery.getRemark());
                    tracesResponse.setAcceptTime(orderBaleDelivery.getLogisticsTime());
                    traces.add(tracesResponse);
                    express.setTraces(traces);
                });
            } else {
                express.setTraces(new ArrayList<>());
            }
            orderItemResponse.setExpress(express);
        } else {
            orderItemResponse.setExpress(new ExpressResponse());
        }
        return orderItemResponse;
    }

}
